package com.zsj.comminlibrary.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;

import static org.greenrobot.eventbus.EventBus.TAG;

public class WifiUtil {
    /**
     * 判断wifi是否打开
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean getWifiEnabled(Context context) {
        @SuppressLint("WifiManagerLeak")
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }

    /**
     * wifi加密方式有5种
     * 0 - WPA/WPA2 PSK
     * 1 - WPA2 PSK
     * 2 - WPA PSK
     * 3 - WEP
     * 4 - NONE
     *
     * @param capabilitie
     * @return
     */
    public static int getWifiEncryptType(String capabilitie) {
        if (TextUtils.isEmpty(capabilitie)) return -1;

        int encryptType;

        if (capabilitie.contains("WPA") && capabilitie.contains("WPA2")) {
            encryptType = 0;
        } else if (capabilitie.contains("WPA2")) {
            encryptType = 1;
        } else if (capabilitie.contains("WPA")) {
            encryptType = 2;
        } else if (capabilitie.contains("WEP")) {
            encryptType = 3;
        } else {
            encryptType = 4;
        }

        return encryptType;
    }

    /**
     * 打开或关闭wifi
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>}</p>
     *
     * @param enabled {@code true}: 打开<br>{@code false}: 关闭
     */
    public static void setWifiEnabled(Context context, final boolean enabled) {
        @SuppressLint("WifiManagerLeak")
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (enabled) {
            if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
            }
        } else {
            if (wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(false);
            }
        }
    }


    /**
     * @param context
     * @param ssid
     * @des 连接已经保存过配置的wifi
     */
    public static void connectWifi(Context context, String ssid) {

        Log.d(TAG, "connectWifi: 去连接wifi: " + ssid);

        if (!getWifiEnabled(context)) return;

        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration wc = new WifiConfiguration();

        wc.SSID = "\"" + ssid + "\"";

        WifiConfiguration configuration = getWifiConfig(context, ssid);
        if (configuration != null) {
            wm.enableNetwork(configuration.networkId, true);
        }

    }

    /**
     * @param context
     * @param ssid
     * @param password
     * @param encryptType
     * @des 连接没有配置过的wifi
     */
    public static void connectWifi(Context context, String ssid, String password, int encryptType) {

        Log.d(TAG, "connectWifi: 去连接wifi: " + ssid);

        if (!getWifiEnabled(context)) return;

        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration wc = new WifiConfiguration();
        wc.allowedAuthAlgorithms.clear();
        wc.allowedGroupCiphers.clear();
        wc.allowedKeyManagement.clear();
        wc.allowedPairwiseCiphers.clear();
        wc.allowedProtocols.clear();

        wc.SSID = "\"" + ssid + "\"";

        WifiConfiguration configuration = getWifiConfig(context, ssid);
        if (configuration != null) {
            wm.removeNetwork(configuration.networkId);
        }

        switch (encryptType) {
            case 4://不加密
                wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;

            case 3://wep加密
                wc.hiddenSSID = true;
                wc.wepKeys[0] = "\"" + password + "\"";
                wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

                break;
            case 0: //wpa/wap2加密
            case 1: //wpa2加密
            case 2: //wpa加密

                wc.preSharedKey = "\"" + password + "\"";
                wc.hiddenSSID = true;
                wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                wc.status = WifiConfiguration.Status.ENABLED;
                break;
        }

        int network = wm.addNetwork(wc);
        wm.enableNetwork(network, true);
    }

    public static void disConnectWifi(Context context, int networkId) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        wm.disableNetwork(networkId);
        wm.disconnect();
    }


    /**
     * @param context
     * @param ssid
     * @des 清除wifi配置信息
     */
    public static void clearWifiInfo(Context context, String ssid) {

        Log.d(TAG, "clearWifiInfo: 清除WIFI配置信息: " + ssid);

        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        String newSSID = "\"" + ssid + "\"";

        if (!(ssid.startsWith("\"") && ssid.endsWith("\""))) {
            newSSID = "\"" + ssid + "\"";
        } else {
            newSSID = ssid;
        }

        WifiConfiguration configuration = getWifiConfig(context, newSSID);
        if (configuration == null) {
            return;
        }
        wm.disableNetwork(configuration.networkId);
        wm.disconnect();
        configuration.allowedAuthAlgorithms.clear();
        configuration.allowedGroupCiphers.clear();
        configuration.allowedKeyManagement.clear();
        configuration.allowedPairwiseCiphers.clear();
        configuration.allowedProtocols.clear();

        if (configuration != null) {

            wm.removeNetwork(configuration.networkId);
            wm.saveConfiguration();
        }
    }

    public static WifiConfiguration getWifiConfig(Context context, String ssid) {

        Log.d(TAG, "getWifiConfig: 获取wifi配置信息: " + ssid);

        if (TextUtils.isEmpty(ssid)) return null;

        String newSSID;

        if (!(ssid.startsWith("\"") && ssid.endsWith("\""))) {
            newSSID = "\"" + ssid + "\"";
        } else {
            newSSID = ssid;
        }

        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configuredNetworks = wm.getConfiguredNetworks();

        for (WifiConfiguration configuration : configuredNetworks) {
            if (newSSID.equalsIgnoreCase(configuration.SSID)) {
                return configuration;
            }
        }

        return null;
    }

}
